package com.example.shgt;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import okhttp3.MediaType;
import okhttp3.RequestBody; // 确保导入 RequestBody
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MessageDetailActivity extends AppCompatActivity {

    private RecyclerView recyclerViewMessages;
    private MessageDetailAdapter messageDetailAdapter;
    private List<MessageDetail> messageDetailList;

    private EditText editTextMessage; // 添加 EditText
    private Button buttonSend; // 添加 Button



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 创建布局
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);

        // 获取 fromUserId
        String fromUserId = getIntent().getStringExtra("fromUserId");

        //获取 sellerID
        String sellerId = getIntent().getStringExtra("sellerId");
        Log.d("MessageDetailActivity", "Received sellerId: " + sellerId);

        // 创建 RecyclerView
        recyclerViewMessages = new RecyclerView(this);
        recyclerViewMessages.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                0, // 让 RecyclerView 占据剩余空间
                1 // 使用权重
        ));
        layout.addView(recyclerViewMessages);

        // 初始化消息详情列表和适配器
        messageDetailList = new ArrayList<>();
        messageDetailAdapter = new MessageDetailAdapter(messageDetailList);
        recyclerViewMessages.setAdapter(messageDetailAdapter);
        recyclerViewMessages.setLayoutManager(new LinearLayoutManager(this));

        // 创建输入区域
        LinearLayout inputLayout = new LinearLayout(this);
        inputLayout.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout.LayoutParams inputLayoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        inputLayout.setLayoutParams(inputLayoutParams);

        // 输入框
        editTextMessage = new EditText(this);
        editTextMessage.setLayoutParams(new LinearLayout.LayoutParams(
                0, // 宽度为0
                LinearLayout.LayoutParams.WRAP_CONTENT,
                1 // 权重为1，让它占据可用空间
        ));
        editTextMessage.setHint("输入消息");
        inputLayout.addView(editTextMessage);

        // 发送按钮
        buttonSend = new Button(this);
        buttonSend.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        ));
        buttonSend.setText("发送");
        inputLayout.addView(buttonSend);

        layout.addView(inputLayout); // 将输入区域添加到布局中

        // 获取消息详情
        if (fromUserId != null) {
            fetchMessageDetails(fromUserId);
        }
        if (sellerId != null) {
            fetchMessageDetails(sellerId);
        } else {
            Toast.makeText(this, "无效的商家ID", Toast.LENGTH_SHORT).show();
        }

        // 设置发送按钮点击事件
        buttonSend.setOnClickListener(v -> {
            String message = editTextMessage.getText().toString().trim();
            if (!message.isEmpty()) {
                // 处理发送消息的逻辑
                sendMessage(message, fromUserId);
                editTextMessage.setText(""); // 清空输入框
            }

            if (!message.isEmpty()) {
                // 处理发送消息的逻辑
                sendMessage(message, sellerId);
                editTextMessage.setText(""); // 清空输入框
            }

        });
    }

    private void fetchMessageDetails(String fUserId) {
        // 从 SharedPreferences 获取当前登录用户的 ID
        String userId = getSharedPreferences("UserPrefs", MODE_PRIVATE).getString("userId", null);

        // 记录 fromUserId 和 userId 的值
        Log.d("MessageDetailActivity", "fromUserId: " + fUserId + ", userId: " + userId);

        // 使用正确的参数顺序
        String url = "https://api-store.openguet.cn/api/member/tran/chat/message?fromUserId=" + fUserId + "&userId=" + userId;
        Log.d("MessageDetailActivity", "Request URL: " + url); // 打印请求的 URL

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Content-Type", "application/json")
                .addHeader("appId", "479dbe79299a4653ada0432942111871")
                .addHeader("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    Log.d("MessageDetailActivity", "Response Data: " + responseData);
                    parseResponseData(responseData); // 调用解析方法
                } else {
                    Log.e("MessageDetailActivity", "Response error: " + response.code());
                }
            }
        });
        // 假设获取消息后刷新适配器
        runOnUiThread(() -> messageDetailAdapter.notifyDataSetChanged());
    }

    private void parseResponseData(String responseData) {
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(responseData, JsonObject.class);

        // 检查返回的 JSON 是否包含 "data" 和 "records"
        if (jsonObject.has("data") && jsonObject.get("data").isJsonObject()) {
            JsonObject dataObject = jsonObject.getAsJsonObject("data");
            if (dataObject.has("records") && dataObject.get("records").isJsonArray()) {
                JsonArray recordsArray = dataObject.getAsJsonArray("records");

                messageDetailList.clear();
                for (JsonElement element : recordsArray) {
                    JsonObject detailObject = element.getAsJsonObject();
                    String messageText = detailObject.get("content").getAsString(); // 获取消息文本
                    String fromUsername = detailObject.get("fromUsername").getAsString(); // 获取发件人用户名
                    String createTime = detailObject.get("createTime").getAsString(); // 获取创建时间

                    // 格式化时间
                    String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(createTime)));

                    messageDetailList.add(new MessageDetail(messageText, fromUsername, formattedDate));
                }

                runOnUiThread(() -> messageDetailAdapter.notifyDataSetChanged());
            } else {
                Log.e("MessageDetailActivity", "响应中未包含有效的记录数组。");
            }
        } else {
            Log.e("MessageDetailActivity", "响应中未包含有效的数据对象。");
        }
    }

    private void sendMessage(String message, String toUserId) {
        // 从 SharedPreferences 获取当前登录用户的 ID
        String userId = getSharedPreferences("UserPrefs", MODE_PRIVATE).getString("userId", null);

        if (userId != null) {
            // 创建 JSON 对象，包含请求参数
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("content", message);
            jsonObject.addProperty("toUserId", toUserId);
            jsonObject.addProperty("userId", userId);

            // 创建请求体
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());

            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("https://api-store.openguet.cn/api/member/tran/chat")
                    .post(requestBody) // 使用 POST 方法
                    .addHeader("Accept", "application/json, text/plain, */*")
                    .addHeader("Content-Type", "application/json")
                    .addHeader("appId", "479dbe79299a4653ada0432942111871")
                    .addHeader("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                    .build();

            // 发送请求
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    Log.e("MessageDetailActivity", "发送消息失败: " + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String responseData = response.body().string();
                        Log.d("MessageDetailActivity", "发送消息成功: " + responseData);
                    } else {
                        Log.e("MessageDetailActivity", "发送消息失败: " + response.code());
                    }
                }
            });
        } else {
            Log.e("MessageDetailActivity", "获取 userId 失败");
        }
    }




    // 获取当前时间的帮助方法
    private String getCurrentTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

}

// 消息详情模型类
class MessageDetail {
    private String message;
    private String fromUsername;
    private String createTime;

    public MessageDetail(String message, String fromUsername, String createTime) {
        this.message = message;
        this.fromUsername = fromUsername;
        this.createTime = createTime;
    }

    public String getMessage() {
        return message;
    }

    public String getFromUsername() {
        return fromUsername;
    }

    public String getCreateTime() {
        return createTime;
    }
}

// 消息详情适配器
class MessageDetailAdapter extends RecyclerView.Adapter<MessageDetailAdapter.MessageDetailViewHolder> {
    private List<MessageDetail> messageDetails;

    public MessageDetailAdapter(List<MessageDetail> messageDetails) {
        this.messageDetails = messageDetails;
    }

    @NonNull
    @Override
    public MessageDetailViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message_detail, parent, false);
        return new MessageDetailViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MessageDetailViewHolder holder, int position) {
        MessageDetail detail = messageDetails.get(position);
        holder.textViewMessage.setText(detail.getMessage());
        holder.textViewFromUsername.setText(detail.getFromUsername());
        holder.textViewCreateTime.setText(detail.getCreateTime());
    }

    @Override
    public int getItemCount() {
        return messageDetails.size();
    }

    public static class MessageDetailViewHolder extends RecyclerView.ViewHolder {
        TextView textViewMessage;
        TextView textViewFromUsername;
        TextView textViewCreateTime;

        public MessageDetailViewHolder(@NonNull View itemView) {
            super(itemView);
            textViewMessage = itemView.findViewById(R.id.tv_message_detail);
            textViewFromUsername = itemView.findViewById(R.id.tv_from_username);
            textViewCreateTime = itemView.findViewById(R.id.tv_create_time);
        }
    }
}
